<?php

namespace Ignus\View\Node\Expression;

use Ignus\View\Node\Expression;
use Ignus\View\Compiler;
use Ignus\View\NodeInterface;
use Ignus\View\Error\Syntax;

class FunctionExpr extends Expression
{
    public function __construct($name, NodeInterface $arguments, $lineno)
    {
        parent::__construct(array('arguments' => $arguments), array('name' => $name), $lineno);
    }

    public function compile(Compiler $compiler)
    {
        $function = $compiler->getEnvironment()->getFunction($this->getAttribute('name'));
        if (false === $function) {
            throw new Syntax(sprintf('The function "%s" does not exist', $this->getAttribute('name')), $this->getLine());
        }

        $compiler
            ->raw($function->compile().'(')
            ->raw($function->needsEnvironment() ? '$this->env' : '');

        if ($function->needsContext()) {
            $compiler->raw($function->needsEnvironment() ? ', $context' : '$context');
        }

        $first = true;
        foreach ($this->getNode('arguments') as $node) {
            if (!$first) {
                $compiler->raw(', ');
            }
            else {
                if ($function->needsEnvironment() || $function->needsContext()) {
                    $compiler->raw(', ');
                }
                $first = false;
            }
            $compiler->subcompile($node);
        }

        $compiler->raw(')');
    }
}
